package org.firebug.spring.boot.scheduler;

import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@EnableScheduling
@EnableAsync
public class Scheduler {

    /** 开启多线程任务调度 */
    @Bean(name = "taskScheduler")
    public TaskScheduler getTaskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(42);
        return taskScheduler;
    }

    @Async
    @Scheduled(initialDelay = 1000, fixedRate = 1000)
    public void rate() throws InterruptedException {
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println(Thread.currentThread() + " rate: " + time);
        Thread.sleep(2000L);
    }

    @Async
    @Scheduled(initialDelay = 1000, fixedDelay = 1000)
    public void delay() throws InterruptedException {
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println(Thread.currentThread() + " delay: " + time);
        Thread.sleep(2000L);
    }

    @Async
    @Scheduled(zone = "GMT+8", cron = "* * * * * *")
    public void cron() throws InterruptedException {
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println(Thread.currentThread() + " cron: " + time);
        Thread.sleep(2000L);
    }
}
